package utils;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

public class ConfigUtil {
	private static final String ADDR = "./resource/config.properties";

	public static Map<String,String> getConf(){
		return readConf();
	}
	public static Map<String,String> getConfByAddr(String addr){
		return readConfByAddr(addr);
	}
	public static String getConf(String key){
		return (String)readConf().get(key);
	}
	public static String getConfByAddr(String addr,String key){
		return (String)readConfByAddr(addr).get(key);
	}
	public static Integer getConf2Int(String key){
		return Integer.valueOf(readConf().get(key));
	}
	public static Integer getConf2IntByAddr(String addr,String key){
		return Integer.valueOf(readConfByAddr(addr).get(key));
	}
	public static Date getConf2Date(String key){
		String val = readConf().get(key);
		return parseDate(val);
	}
	public static Date getConf2DateByAddr(String addr,String key){
		String val = readConfByAddr(addr).get(key);
		return parseDate(val);
	}
	private static Date parseDate(String val){
		SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
		Date date = null;
		try{
			date = sdf1.parse(val);
		}catch (Exception e1) {
			try{
				date = sdf2.parse(val);
			}catch (Exception e2) {
			}
		}
		return date;
	}
	private static Map<String,String> readConf(){
		return readConfByAddr(ADDR);
	}
	private static Map<String,String> readConfByAddr(String addr){
		Properties pps = new Properties();
		Map<String,String> conf = new HashMap<String,String>();
		try {
			pps.load(new FileInputStream(addr));
			Enumeration enum1 = pps.propertyNames();//得到配置文件的名字
			while(enum1.hasMoreElements()) {
			 String strKey = (String) enum1.nextElement();
			 String strValue = pps.getProperty(strKey);
			 conf.put(strKey, strValue);
			}
		} catch (FileNotFoundException e) {
		} catch (IOException e) {
		}
		return conf;
	}
	public static void main(String[] args) throws Exception, IOException {
		Integer name = getConf2IntByAddr("./resource/config.properties","name");
		System.out.println(name);
		Date date = getConf2DateByAddr("./resource/config1.properties","date");
		System.out.println(date);
	}
}
